#!/bin/sh
set -e
MYDIR="${0%/*}"
cd "${MYDIR}"
if [ ! -d "recipes" ]; then
	mkdir -p recipes
fi

extract_body() {
	local started=0
	local finished=0
	local pkg="$1"

	while read line; do
		if test "x$started" = x0; then
			case "$line" in
			'# ''RECIPE START '"$pkg")
				started=1
				echo "$line"
				;;
			*)
				;;
			esac
		elif test "x$finished" = x0; then
			case "$line" in
			'# ''RECIPE END '"$pkg")
				echo "$line"
				break
				;;
			*)
				echo "$line"
				;;
			esac
		elif test "x$finished" = x1; then
			break
		fi
	done < bootstrap.sh
}

mk_header () {
	local pkg="$1"
	if [ x"$pkg" = 'xcommon' ]; then
		cat <<-EOF
		#!/bin/echo this scriptlet should be sourced by a build recipe
		EOF
		return
	fi
	
	cat <<-EOF
	#!/bin/sh
	set -e
	set -x
	MYDIR="\${0%/*}"
	cd "\$MYDIR/.."
	source "recipes/common.sh"

	EOF
}

main () {
	local pkg="$1"
	local recipe="recipes/${pkg}.sh"
	local recipe_tmp="${recipe}.$$"

	if [ -z "$pkg" ]; then
		echo "** Error: package is not specified" >&2
		exit 1
	fi

	mk_header "$pkg" > "${recipe_tmp}"
	extract_body "$pkg" >> "${recipe_tmp}"
	chmod 755 "$recipe_tmp"
	mv "$recipe_tmp" "$recipe"
}

main "$1"

